package com.mooc.swxy.control;

import com.mooc.swxy.system.ReqURL;
import com.mooc.swxy.system.ResponseMap;
import com.mooc.swxy.tool.RequestTool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;


/**
 * @author Siaze
 * @date 2022/4/19
 * 用户可以通过该方法从网课平台登录获取token
 */
@RestController
public class Login {

    private static final Logger logger = LoggerFactory.getLogger(Login.class);

    @Autowired
    private RequestTool requestTool;

    /**
     * 用户可以通过该方法从网课平台登录
     * @param params    Map包括用户的账号、密码、验证码
     * @param token     token（未验证通过获取验证码的token）
     * @return 登录结果
     */
    @PostMapping("/login")
    public ResponseMap login(@RequestBody Map<String,String> params, @CookieValue("token") String token) {
        String response = requestTool.postRequest(ReqURL.BASE_URL.concat(ReqURL.LOGIN_URL), MediaType.APPLICATION_FORM_URLENCODED, params, token, String.class);
        return response.contains("登录成功") ? new ResponseMap(200, "登录成功") : new ResponseMap(400, "登录失败");
    }


    /**
     * 用户可以通过该方法获取token
     * @return token
     */
    @GetMapping("/getToken")
    public ResponseMap getToken(HttpServletRequest request) {
        for (Cookie cookie : request.getCookies()){
            if("token".equals(cookie.getName())){
                return new ResponseMap(200,"获取token成功").putData("token",cookie.getValue());
            }
        }
        return new ResponseMap(200,"获取token失败");
    }

    /**
     * 用户可以通过该方法从网课平台登录验证码
     * @return 验证码图片
     */
    @GetMapping(value = "/getImg", produces = MediaType.IMAGE_PNG_VALUE)
    public byte[] getImg(HttpServletResponse response) {
        //发送网络请求获取token
        ResponseEntity<byte[]> forEntity = requestTool.getForEntity(ReqURL.BASE_URL.concat(ReqURL.CODE_URL), byte[].class);
       //获取响应头返回的token，并将token放入cookie中
        List<String> headers = forEntity.getHeaders().get("Set-Cookie");
        logger.info(headers.toString());
        for (String header : headers) {
            if (header.startsWith("token")) {
                logger.info(String.valueOf(header.split("=")[1]));
                response.addHeader(HttpHeaders.SET_COOKIE, header.split(";")[0]);
            }
        }
        return forEntity.getBody();
    }
}
